package com.konsung.ksdc.manager.shop;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.netbean.AddrInfoNetBean;
import com.konsung.ksdc.bean.netbean.CartDetailNetBean;
import com.konsung.ksdc.bean.netbean.ProductDetailNetBean;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.PreferenceUtils;
import com.konsung.ksdc.common.utils.StringUtils;
import com.konsung.ksdc.common.utils.ToastUtils;
import com.konsung.ksdc.common.widget.ExpandListView;
import com.konsung.ksdc.common.widget.OnMultiClickListener;
import com.konsung.ksdc.common.widget.WaitingDialog;
import com.konsung.ksdc.config.MyApplication;
import com.konsung.ksdc.config.NetConfig;
import com.konsung.ksdc.manager.addr.AddrActivity;
import com.konsung.ksdc.manager.appmain.BaseActivity;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 确认订单页面
 * Created by Administrator on 2016/5/10 0010.
 */
public class OrderConfirmActivity extends BaseActivity {
    public static final String DATA_BUY_LIST = "data_buy_list";
    public static final int REQUEST_CODE = 10010;
    public static final String ADDR_DATA = "addr_data";
    public static final String TYPE_BUY = "type_buy";
    public static final int TYPE_BUY_DIRECT = 10100; // 立即购买
    public static final int TYPE_BUY_CART = 10200; // 购物车购买
    public static final String SHOPPING_NUM = "shoppingNum";
    public static final String PRODUCT_NET_BEAN = "productNetBean";
    public static final String PRODUCT_ICON_URL = "productIconUrl";
    public static final String CART_IDS = "cart_ids";
    public static final String ADDR_BEAN = "addr_bean";
    public static final String KEY_DATA = "datas";
    private static final String SHOP_CART_EMPTY = "0";

    @Bind(R.id.rl_back)
    RelativeLayout rlBack;
    @Bind(R.id.tab_tv_title)
    TextView tabTvTitle;
    @Bind(R.id.rl_title_container)
    RelativeLayout rlTitleContainer;
    @Bind(R.id.lv_buy_list)
    ExpandListView lvBuyList;
    @Bind(R.id.tv_sum)
    TextView tvSum;
    @Bind(R.id.btn_commit_order)
    Button btnCommitOrder;
    @Bind(R.id.ll_addr_container)
    LinearLayout llAddrContainer;
    @Bind(R.id.tv_receiver)
    TextView tvReceiver;
    @Bind(R.id.tv_phone)
    TextView tvPhone;
    @Bind(R.id.tv_addr_detail)
    TextView tvAddrDetail;
    @Bind(R.id.iv_product)
    ImageView ivProduct;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_subtitle)
    TextView tvSubtitle;
    @Bind(R.id.tv_price)
    TextView tvPrice;
    @Bind(R.id.tv_num)
    TextView tvNum;
    @Bind(R.id.rl_direct_but_container)
    RelativeLayout rlDirectButContainer;
    @Bind(R.id.tv_save)
    TextView tvSave;
    @Bind(R.id.iv_counsel)
    ImageView ivCounsel;
    @Bind(R.id.addr_info_container)
    LinearLayout addrInfoContainer;
    @Bind(R.id.ll_empty_address)
    LinearLayout llEmptyAddress;
    @Bind(R.id.tv_count_text)
    TextView tvCountText;
    @Bind(R.id.tv_pay_text)
    TextView tvPayText;

    private ArrayList<CartDetailNetBean> datas = new ArrayList<>();
    private double sum;
    private AddrInfoNetBean currentAddrNetBean; //当前页面中显示的地址bean数据
    private ProductDetailNetBean productDetailNetBean;
    private int shoppingNum;
    private double price;
    private int type;
    private String carIds;
    private WaitingDialog dialog;

    @Override
    protected String activityDesc() {
        return getString(R.string.page_confirm_order);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_order);

        ButterKnife.bind(this);

        initData();
        initView();
    }

    /**
     * 初始化确认订单页面数据
     */
    private void initData() {
        lvBuyList.setFocusable(false);
        datas = getIntent().getParcelableArrayListExtra(KEY_DATA);
        sum = getIntent().getDoubleExtra(ShoppingCartActivity
                .KEY_SUM, 0.00);

        // 网络获取默认的地址数据并显示
        if (!RequestUtils.checkNetwork(OrderConfirmActivity.this)) {
            return;
        }
        getDefaultAddr();
        // 根据进入的type，加载不同的数据，显示不同的条目（direct或cart）
        type = getIntent().getIntExtra(TYPE_BUY, TYPE_BUY_DIRECT);
        switch (type) {
            case TYPE_BUY_DIRECT:

                lvBuyList.setVisibility(View.GONE);
                rlDirectButContainer.setVisibility(View.VISIBLE);
                productDetailNetBean = getIntent().
                        getParcelableExtra(PRODUCT_NET_BEAN);

                if (productDetailNetBean != null) {
                    String productName = productDetailNetBean.getProductName();
                    String subTitle = productDetailNetBean.getSubTitle();
                    String marketPrice = productDetailNetBean.getMemberPrice();
                    shoppingNum = getIntent().getIntExtra(SHOPPING_NUM, 1);

                    String productIconUrl = getIntent()
                            .getStringExtra(PRODUCT_ICON_URL);

                    Picasso.with(this)
                            .load(StringUtils.appendPicPath(productIconUrl))
                            .placeholder(R.drawable.pic_talkbox_sel)
                            .error(R.drawable.pic_talkbox_sel)
                            .into(ivProduct);
                    tvTitle.setText(productName);
                    tvSubtitle.setText(subTitle);

                    tvNum.setText("" + shoppingNum);

                    price = Double.valueOf(marketPrice);
                    double sum = shoppingNum * price;

                    tvPrice.setText(StringUtils.appendPay(price));

                    tvSum.setText(StringUtils.appendPay(sum));
                    tvCountText.setText(StringUtils.appendCount(1));
                    tvPayText.setText(StringUtils.appendPay(sum));
                }

                break;
            case TYPE_BUY_CART:
                Constants.isCartSubmit = true;
                lvBuyList.setVisibility(View.VISIBLE);
                rlDirectButContainer.setVisibility(View.GONE);
                tvCountText.setText(StringUtils.appendCount(datas.size()));
                tvPayText.setText(StringUtils.appendPay(sum));
                tvSum.setText(StringUtils.appendPay(sum));

                carIds = appendProductId(datas);

                break;
            default:
                break;
        }
    }

    /**
     * 拼接商品id
     * @param beanList 需要购买的商品集合
     * @return 拼接后的id
     */
    private String appendProductId(List<CartDetailNetBean> beanList) {
        //遍历购物车，赋值
        StringBuilder builder = new StringBuilder();
        for (CartDetailNetBean bean : beanList) {
            String catId = bean.getCatId();
            builder.append(catId).append("-");
        }
        builder.deleteCharAt(builder.length() - 1);
        return builder.toString();
    }

    /**
     * 获取默认收货地址
     */
    private void getDefaultAddr() {
        RequestUtils.getDefaultAddress(
                NetConfig.currentUser.getUserId(),
                new RequestCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {

                        String resultCode =
                                responseBean.getResultCode();
                        if (resultCode.equals(Constants.REQUEST_OK)) {

                            // todo 假如没有默认地址，没有地址数据 判空处理
                            currentAddrNetBean = responseBean.
                                    getEntity(AddrInfoNetBean.class);
                            if (currentAddrNetBean != null) {
                                String userName = currentAddrNetBean
                                        .getUserName();
                                String phone = currentAddrNetBean
                                        .getPhone();
                                String detailAddress = currentAddrNetBean.
                                        getDetailAddress();
                                String detailAddr = detailAddress
                                        .replace("&", "");

                                tvReceiver.setText(userName);
                                tvPhone.setText(phone);
                                tvAddrDetail.setText(detailAddr);

                                llEmptyAddress.setVisibility(View.GONE);
                                addrInfoContainer.setVisibility(View.VISIBLE);
                            } else {
                                tvReceiver.setText("");
                                tvPhone.setText("");
                                tvAddrDetail.setText("");

                                addrInfoContainer.setVisibility(View.GONE);
                                llEmptyAddress.setVisibility(View.VISIBLE);
                            }
                        }
                    }
                });
    }

    /**
     * 初始化确认订单页面
     */
    private void initView() {
        tabTvTitle.setText(R.string.title_confirm_order);
        rlBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        lvBuyList.setAdapter(new ConfirmBuyListAdapter(datas));
        llAddrContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(OrderConfirmActivity.this,
                        AddrActivity.class);
                startActivityForResult(intent, REQUEST_CODE);
            }
        });

        btnCommitOrder.setOnClickListener(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {

                int visibility = llEmptyAddress.getVisibility();
                if (visibility == View.VISIBLE) {
                    Toast.makeText(MyApplication.getContext(), R.string.tip_addr_empty,
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                if (currentAddrNetBean == null) {
                    Toast.makeText(MyApplication.getContext(), R.string.tip_addr_empty,
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                dialog = new WaitingDialog(OrderConfirmActivity.this, "");
                dialog.setText(getString(R.string.submitting));
                dialog.show();
                switch (type) {
                    case TYPE_BUY_DIRECT:
                        requestAddOrderDirect();
                        break;
                    case TYPE_BUY_CART:
                        requestAddOrderCart();
                        break;
                    default:
                        ToastUtils.toastContent(MyApplication
                                .getContext(), getString(R.string.tip_addr_empty));
                        dialog.dismiss();
                        break;
                }
            }
        });
    }

    /**
     * 发送请求添加订单（购物车购买）
     */
    private void requestAddOrderCart() {

        RequestUtils.addOrderFromCat(
                NetConfig.currentUser.getUserId(),
                currentAddrNetBean.getAddressId(), carIds,
                new RequestCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        Toast.makeText(OrderConfirmActivity.this,
                                R.string.tip_commit_order_error,
                                Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        String resultCode = responseBean.getResultCode();
                        dialog.dismiss();
                        if (resultCode.equals(Constants.REQUEST_OK)) {
                            //提交订购成功后，把对应的购物车本地数据清除为0
                            for (CartDetailNetBean bean : datas) {
                                PreferenceUtils.putString(OrderConfirmActivity.this,
                                        bean.getProductName(), SHOP_CART_EMPTY);
                            }
                            //提交菜单后，Editext先显示，后隐藏，不然会陷入死循环，退到购物车，Editext屏蔽掉
                            Constants.isHideBuyList = true;
                            String orderId = responseBean.getEntity(String.class);
                            Intent intent = new Intent(
                                    OrderConfirmActivity.this,
                                    OrderCommitOkActivity.class);
                            intent.putParcelableArrayListExtra(
                                    DATA_BUY_LIST, datas);
                            intent.putExtra(ADDR_BEAN, currentAddrNetBean);
                            intent.putExtra(OrderCommitOkActivity.ORDER_TYPE, "1");
                            intent.putExtra(OrderCommitOkActivity.ORDER_ID, orderId);
                            startActivity(intent);
                            finish();
                        } else {
                            Toast.makeText(OrderConfirmActivity.this, responseBean
                                    .getEntity(String.class), Toast.LENGTH_SHORT).show();
                        }
                    }
                }
        );
    }

    /**
     * 发送请求添加订单（直接购买）
     */
    private void requestAddOrderDirect() {
        if (productDetailNetBean != null) {
            RequestUtils.addOrderForDirect(NetConfig.currentUser.getUserId(),
                    productDetailNetBean.getMarketPrice(),
                    productDetailNetBean.getProductId(), "" + shoppingNum,
                    currentAddrNetBean.getAddressId(),
                    Constants.ORDER_TYPE_NOT_SEND, new RequestCallback() {
                        @Override
                        public void onError(Call call, Exception e) {
                            Toast.makeText(OrderConfirmActivity.this,
                                    R.string.tip_commit_order_error,
                                    Toast.LENGTH_SHORT).show();
                            dialog.dismiss();
                        }

                        @Override
                        public void onResponse(ResponseBean responseBean) {
                            String resultCode = responseBean.getResultCode();
                            dialog.dismiss();
                            if (resultCode.equals(Constants.REQUEST_OK)) {
                                String orderId = responseBean.getEntity(String.class);
                                Intent intent = new Intent(
                                        OrderConfirmActivity.this,
                                        OrderCommitOkActivity.class);
                                intent.putParcelableArrayListExtra(
                                        DATA_BUY_LIST, datas);
                                intent.putExtra(ADDR_BEAN, currentAddrNetBean);
                                intent.putExtra(OrderCommitOkActivity.ORDER_TYPE, "1");
                                intent.putExtra(OrderCommitOkActivity.ORDER_ID, orderId);
                                startActivity(intent);
                                finish();
                            } else {
                                Toast.makeText(OrderConfirmActivity.this,
                                        responseBean.getEntity(String.class),
                                        Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        } else {
            Toast.makeText(OrderConfirmActivity.this,
                    getString(R.string.tip_product_no),
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode,
            int resultCode, Intent data) {
        if (data == null || "".equals(data)) {
            return;
        } else {
            currentAddrNetBean = data.
                    getParcelableExtra(ADDR_DATA);

            tvReceiver.setText(currentAddrNetBean.getUserName());
            String phone = currentAddrNetBean.getPhone();
            tvPhone.setText(phone);
            String detailAddress = currentAddrNetBean.getDetailAddress();
            String detailAddr = detailAddress.replace("&", "");
            tvAddrDetail.setText(detailAddr);

            llEmptyAddress.setVisibility(View.GONE);
            addrInfoContainer.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        RequestUtils.findAddress(NetConfig.currentEmpid,
                new RequestCallback() {

                    @Override
                    public void onError(Call call, Exception e) {
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        List<AddrInfoNetBean> addressList = responseBean.getList(new
                                TypeToken<List<AddrInfoNetBean>>() {
                                }.getType());
                        if (null == addressList || addressList.size() == 0) {
                            llEmptyAddress.setVisibility(View.VISIBLE);
                            addrInfoContainer.setVisibility(View.GONE);
                            return;
                        }
                        boolean deleted = true;
                        for (AddrInfoNetBean bean : addressList) {
                            if (null != currentAddrNetBean && currentAddrNetBean.getAddressId()
                                    .equals(bean.getAddressId())) {
                                deleted = false;
                            }
                        }
                        if (deleted) {
                            llEmptyAddress.setVisibility(View.VISIBLE);
                            addrInfoContainer.setVisibility(View.GONE);
                        } else {
                            llEmptyAddress.setVisibility(View.GONE);
                            addrInfoContainer.setVisibility(View.VISIBLE);
                        }
                    }
                });
    }
}
